import axios from 'axios'
import qs from 'qs'
import { message } from 'ant-design-vue';
import VueCookies from 'vue-cookies';
export const baseURL = import.meta.env.VITE_APP_BASE_URL;

const request = axios.create({
	baseURL,
	timeout: 50000
})

//request.defaults.timeout = 10000
request.defaults.headers = {
	'Content-Type': 'application/x-www-form-urlencoded',
	'Authorization': ''
}

//增加拦截器
request.interceptors.request.use(config => {
	if (config.method === 'post' && config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
		config.data = qs.stringify(config.data);
	}

	//添加token
	const token = VueCookies.get('token');

	//aliyun oss cors
	if (token && config.headers['Authorization'] !== null) {
		config.headers['Authorization'] = 'Bearer ' + token || ''
	}

	return config
}, (error) => {
	return Promise.reject(error)
})

request.interceptors.response.use((res) => {
	return res;
}, (err) => {
	if (err.response.status === 401) {
		message.error('登录信息已失效，请重新登录', 1).then(() => {
			VueCookies.remove('token');

			window.location.replace(`/#/login?t=${Math.random()}`);
			window.location.reload();
		});
	}

	return Promise.reject(err)
})

export default request
